<template>
  <view class="goods-filters">
    <view class="search">
      <search @search="onSearch" />
    </view>
    <view class="px-9px text-base h-44px leading-44px">
      <view class="mr-28px" @click="salesClick((sales = !sales))"
        >按销量排序
        <image
          :src="ossImg('others/component/down.png')"
          :style="{
            transform: `rotate(${sales === true ? '180deg' : '0deg'})`,
          }"
        />
      </view>
      <view class="sort" @click="lowestPriceClick((lowestPrice = !lowestPrice))"
        >按价格排序
        <image
          :src="ossImg('others/component/down.png')"
          :style="{
            transform: `rotate(${lowestPrice === true ? '180deg' : '0deg'})`,
          }"
        />
      </view>
    </view>
  </view>
  <view class="goods-list">
    <template v-if="goodsList.list.length > 0">
      <view
        class="recommend-goods"
        v-for="item in goodsList.list"
        :key="item"
        @click="toGoodsDetail(item)"
      >
        <view
          class="recommend-cover cover"
          :style="{ backgroundImage: `url(${item.imageUrl})` }"
        ></view>
        <view class="recommend-content">
          <view class="goods-name">
            {{ item.name }}
          </view>
          <view class="goods-price">
            <view class="price my-8px">
              <view class="master"> {{ item.lowestPrice }}</view>
            </view>
            <view class="reduce"
              ><text
                class="price"
                v-if="item.originalPrice && item.originalPrice > 0"
                >{{ item.originalPrice }}</text
              >
            </view>
          </view>
        </view>
      </view>
    </template>

    <empty-search v-else style="width: 100%" />
  </view>
  <uni-load-more
    class="loadMore"
    v-if="goodsList.list.length !== 0"
    :status="loadingStatus"
    :content-text="contentText"
    @click.stop="scrollChange"
  />

  <back-home :cartCount="cartCount" />


</template>

<script setup>
import { searchGoods } from "@/services/mall";
import Search from "@/components/search";
import BackHome from "@/components/back-home";
import EmptySearch from "@/components/empty-search";
import { ossImg } from "@/utils/utils";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";
import UniLoadMore from "@/components/uni-load-more/uni-load-more.vue";
import privacyPopup from "@/components/privacy-popup";

const cartCount = ref(getApp().globalData.cartCount);

const goodsList = ref({
  total: 0,
  list: [],
});
const sales = ref(true);
const lowestPrice = ref(false);
const keyword = ref("");
const contentText = ref("加载更多");
const loadingStatus = ref("more");
const form = reactive({
  pageNum: 1,
  pageSize: 10,
});

onShow(() => {
  getApp()
    .getCartCount()
    .then((res) => {
      cartCount.value = res;
    });
  getApp().accessLogAdd();
});

onReachBottom(() => {
  scrollChange();
});

const lowestPriceClick = (val) => {
  console.log(val);
  lowestPrice.value = val;
  GetgoodsList(val ? "lowestPrice" : "-lowestPrice");
};

const salesClick = (val) => {
  console.log(val);
  sales.value = val;
  GetgoodsList(val ? "sales" : "-sales");
};

const onSearch = async (val) => {
  console.log(val);
  form.pageNum = 1;
  form.pageSize = 10;
  loadingStatus.value = "more";
  contentText.value = "加载更多";
  keyword.value = val;
  sales.value = true;
  lowestPrice.value = false;

  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "click",
    `page_product_search_${val}`,
    ""
  );

  getApp().sr().track("search", {
    keyword: val,
    // more...
  });
  const res = await searchGoods({
    keyword: val,
    orderBy: sales.value ? "sales" : "-sales",
    ...form,
  });
  if (res?.code === 200) {
    goodsList.value = res.data;
    if (goodsList.value.list.length === goodsList.value.total) {
      loadingStatus.value = "noMore";
      contentText.value = "没有更多";
    }
  }
};

const scrollChange = async () => {
  if (goodsList.value.list.length === goodsList.value.total)
    return (loadingStatus.value = "noMore"), (contentText.value = "没有更多");
  loadingStatus.value = "loading";
  contentText.value = "加载中";
  form.pageNum++;
  const res = await searchGoods({
    keyword: keyword.value,
    orderBy: sales.value ? "sales" : "-sales",
    ...form,
  });
  if (res?.code === 200) {
    goodsList.value.list = goodsList.value.list.concat(res.data.list);
    if (goodsList.value.list.length === goodsList.value.total) {
      loadingStatus.value = "noMore";
      contentText.value = "没有更多";
    } else {
      loadingStatus.value = "more";
      contentText.value = "加载更多";
    }

    console.log(goodsList.value);
  }
};

const GetgoodsList = async (orderBy) => {
  const res = await searchGoods({ keyword: keyword.value, orderBy: orderBy });
  if (res?.code === 200) {
    goodsList.value = res.data.list;
  }
};

const toGoodsDetail = async (item) => {
  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "click",
    `product_button_${item.productId}`,
    ""
  );
  for (const res of item.productSkus) {
    getApp()
      .sr()
      .track("trigger_sku_component", {
        sku: {
          sku_id: res.id, // 若商品无sku_id时，可传spu_id信息
          sku_name: skuLabel(res.spData), // 若商品无sku_name时，可传spu_name信息
        },
        spu: {
          spu_id: res.id, // 若商品无spu_id时，可传sku_id信息
          spu_name: skuLabel(res.spData), // 若商品无spu_name时，可传sku_name信息
        },
      });
  }
  uni.navigateTo({ url: `/pages/goods/goods?id=${item.id}` });
};

const skuLabel = (skuData) => {
  return skuData.map(({ value, key }) => `${key}${value}`).join(" ");
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.goods-filters {
  width: 100%;
  background-color: white;
  padding: 10px 12px 0 12px;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
}

.search {
  width: 100%;
  height: 36px;
  background: #f0f1f3;
  border-radius: 3px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  box-sizing: border-box;

  image {
    width: 20px;
    height: 20px;
    display: block;
    margin-right: 10px;
  }
}

.text-base {
  view {
    display: inline-block;

    image {
      width: 7px;
      height: 4px;
      display: inline-block;
      margin-left: 5px;
      vertical-align: middle;
    }
  }
}

.goods-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 100px 10px 10px 10px;
  box-sizing: border-box;
  gap: 10px;
}

.recommend-goods {
  width: 171px;
  max-width: 50%;
  border-radius: 8px;
  overflow: hidden;

  .recommend-cover {
    width: inherit;
    height: 173px;
    background-color: grey;
  }

  .recommend-content {
    width: 100%;
    color: #181a17;
    font-size: 14px;
    background: #ffffff;
    border: 1px solid #f8f8f8;
    box-sizing: border-box;
    padding: 8px;

    .goods-name {
      color: #212421;
      overflow: hidden;
      height: 36px;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .goods-price {
      color: @primary-color;

      view {
        &.reduce {
          font-size: 12px;
          color: #87a5f1;
          text-decoration: line-through;
          height: 12px;
        }
      }
    }
  }
}
</style>
